{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# AutoML - Deploy Dog Breeds\n",
    "\n",
    "### Objective\n",
    "\n",
    "We will continue with the dog breeds model you built over lunch. In this notebook, we will:\n",
    "\n",
    "    1. Deploy the model\n",
    "    2. Do a remote prediction from a python backend\n",
    "    3. Do a remote prediction from a JS frontend\n",
    "\n",
    "### Instructions\n",
    "\n",
    "You will need the Model ID for the model you built over lunch. In pantheon, goto:\n",
    "\n",
    "    1. Artifical Intelligence => Vision\n",
    "    2. From Vision tab, Select AutoML Classification\n",
    "    3. From AutoML Classification tab, select Models\n",
    "    4. Find your model (i.e., Dog Breeds) and verify status is 'Training Successful'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup Environment Variables\n",
    "\n",
    "You will need to setup the environment variables we used in the previous notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set your project ID\n",
    "PROJECT_ID = \"[your-project-id]\" #@param {type:\"string\"}\n",
    "!gcloud config set project $PROJECT_ID\n",
    "\n",
    "# This is the default, don't change it\n",
    "COMPUTE_REGION=\"us-central1\"\n",
    "\n",
    "import sys\n",
    "\n",
    "# If you are running this notebook in Colab, run this cell and follow the\n",
    "# instructions to authenticate your GCP account. This provides access to your\n",
    "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
    "# requests.\n",
    "\n",
    "if 'google.colab' in sys.modules:\n",
    "  from google.colab import auth as google_auth\n",
    "  google_auth.authenticate_user()\n",
    "\n",
    "# If you are running this notebook locally, replace the string below with the\n",
    "# path to your service account key and run this cell to authenticate your GCP\n",
    "# account.\n",
    "else:\n",
    "  %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial\n",
    "\n",
    "### Import libraries and define constants"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# import the Google AutoML client library\n",
    "from google.cloud import automl_v1beta1 as automl"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create and Configure an AutoML instance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an AutoML client\n",
    "client = automl.AutoMlClient()\n",
    "\n",
    "# Derive the full GCP path to the project\n",
    "project_location = client.location_path(PROJECT_ID, COMPUTE_REGION)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set the Full Model ID\n",
    "\n",
    "Use the model ID you found from your GCS console."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set your model ID here\n",
    "model_id=\"[my-model-id]\"\n",
    "\n",
    "# Get the full path of the model.\n",
    "model_full_id = client.model_path(PROJECT_ID, COMPUTE_REGION, model_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deploy the Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Deploy the model.\n",
    "response = client.deploy_model(model_full_id)\n",
    "\n",
    "# Wait for deployment to complete\n",
    "print(response.result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Make a local copy of the test image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "IMAGE_PATH=\"gs://\" + PROJECT_ID + \"-vcm/dog_breeds/fff43b07992508bc822f33d8ffd902ae.jpg\"\n",
    "!gsutil cp $IMAGE_PATH ./"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Make an online Prediction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Specify a path to an Image\n",
    "IMAGE_PATH=\"fff43b07992508bc822f33d8ffd902ae.jpg\"\n",
    "\n",
    "# Get the full path of the model.\n",
    "model_full_id = client.model_path(PROJECT_ID, COMPUTE_REGION, model_id)\n",
    "\n",
    "# Create client for prediction service.\n",
    "prediction_client = automl.PredictionServiceClient()\n",
    "\n",
    "# Read the image and assign to payload.\n",
    "with open(IMAGE_PATH, 'rb') as image_file:\n",
    "    content = image_file.read()\n",
    "payload = {\"image\": {\"image_bytes\": content}}\n",
    "\n",
    "# params is additional domain-specific parameters.\n",
    "# score_threshold is used to filter the result\n",
    "# Initialize params\n",
    "params = {}\n",
    "score_threshold = None\n",
    "if score_threshold:\n",
    "    params = {\"score_threshold\": score_threshold}\n",
    "\n",
    "response = prediction_client.predict(model_full_id, payload, params)\n",
    "print(\"Prediction results:\")\n",
    "for result in response.payload:\n",
    "    print(\"Predicted class name: {}\".format(result.display_name))\n",
    "    print(\"Predicted class score: {}\".format(result.classification.score))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use from Front-End\n",
    "\n",
    "We will show using CURL. \n",
    "\n",
    "TODO:\n",
    "1. Why is model_id blank\n",
    "2. Get the bytes for the payload"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!curl -X POST \\\n",
    "  -H \"Authorization: Bearer $(gcloud auth application-default print-access-token)\" \\\n",
    "  -H \"Content-Type: application/json\" \\\n",
    "  https://automl.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/us-central1/models/${model_id}:predict \\\n",
    "  -d '{ \"payload\" : { \"image\": { \"imageBytes\" : \"/9j/4AAQSkZJRgABAQAAAQ … \"},}}'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Undeploy the Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Undeploy the model.\n",
    "response = client.deploy_model(model_full_id)\n",
    "\n",
    "# Wait for undeployment to complete\n",
    "print(response.result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cleaning up\n",
    "\n",
    "To clean up all GCP resources used in this project, you can [delete the GCP\n",
    "project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7rc2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
